#include <TFile.h>
#include <TTree.h>
#include <TCanvas.h>
#include <TApplication.h>
#include <TH1D.h>
#include <TH2D.h>
#include <TF1.h>
#include <string>
#include <iostream>
using namespace std;

double find_peak(TH1D *h1, double min, double max)
{
    TF1 *f1 = new TF1("f1", "gaus", min, max);
    f1->SetParameters(1, 0, 1);
    h1->Fit(f1, "R");
    return f1->GetParameter(1);
}

void CompareTheIBd()
{
    string HomeDir = "../AnaData/";
    string RootFile = "ToF_Ana_ToFdata_0922.root";
    TFile *f1 = new TFile((HomeDir + RootFile).c_str(), "read");
    TTree *tree;
    f1->GetObject("treeAna_ToF", tree);
    // int MaxSig = 10000;
    // int nSig;
    // short ch[MaxSig], iBd[10000];

    // treeRaw->SetBranchAddress("ch_ToF", ch);
    // treeRaw->SetBranchAddress("iBd_ToF", iBd);
    // treeRaw->SetBranchAddress("nSig", &nSig);
    TCanvas *c1 = new TCanvas("c1", "c1", 800, 600);
    // tree->Print();
    // TH1D *hiBd1 = new TH1D("hiBd1", "hiBd1", 32, 8, 16);
    // TH1D *hiBd2 = new TH1D("hiBd2", "hiBd2", 32, 8, 16);
    // TH2D *Correclation = new TH2D("Correclation", "Correclation", 3, 0, 3, 2, 15, 17);
    // TH2D *Correclation = new TH2D("Correclation", "Correclation", 3, 0, 3, 2, 15, 17);

    // treeRaw->Draw("ch:iBd>>Correclation");
    // int n = 0;
    // for (int i = 0; i < treeRaw->GetEntries(); i++)
    // {

    //     treeRaw->GetEntry(i);
    //     for (int iEvet = 0; iEvet < nSig; iEvet++)
    //     {
    //         if (ch[iEvet] == 15)
    //         {
    //             n++;
    //         }
    //     }
    // }
    // cout << n << endl;
    // c1->Divide(1, 2);
    // c1->cd(1);
    // treeRaw->Draw("ch>>hiBd1", "iBd==1");
    // treeRaw->Draw("coarse>>hiBd1(100000,0,52000)", "iBd==1&&(ch==2||ch==6)");
    // c1->cd(2);
    // treeRaw->Draw("ch>>hiBd2", "iBd==2");
    // cout << find_peak(hiBd2, 12500, 12550);
    // treeRaw->Draw(Form("ch>>hiBd(32,0,32)"));
    // tree->Draw("tmDif[0][0]>>", "");
    int n_iBd0 = 4;
    int n_iBd1 = 14;
    c1->Divide(n_iBd0, n_iBd1);
    for (int i = 0; i < n_iBd0; i++)
    {
        for (int j = 0; j < n_iBd1; j++)
        {
            c1->cd(i * n_iBd1 + j + 1);
            tree->Draw(Form("tmDif[%d][%d]>>h%d(4000,-2,2)", i, j, i * n_iBd1 + j + 1));
        }
    }

    // TH1D *hiBd1 = new TH1D("hiBd1", "hiBd1", 100, 10000, 30000);
    // treeRaw->Project("coarse>>hiBd1", "iBd==1");
    // TH1D *hiBd2 = new TH1D("hiBd2", "hiBd2", 100, 10000, 30000);
    // treeRaw->Project("coarse>>hiBd2", "iBd==2");
    // TCanvas *c1 = new TCanvas("c1", "c1", 800, 600);
    // c1->Divide(1, 2);
    // c1->cd(1);
    // hiBd1->Draw();
    // c1->cd(2);
    // hiBd2->Draw();
    c1->Draw();
    // c1->SaveAs("IBd.png");
}
int main(int argc, char const *argv[])
{
    CompareTheIBd();
    return 0;
}
